<template>
	<view class="page-all">
		<Header :title="title" bgColor="#fff" :leftIconSize="20"></Header>
		<Tabs :list="list"  :current="current"  @changeTab="changeTab"></Tabs>
		<view class="search-content">
			<view class="left">
				<uv-search :placeholder="searchTitle" bgColor="#fff" v-model="queryForm.schoolName"  :showAction="false"  @change="searchFun()" @clear="clearFun()" @blur="searchFun()"></uv-search>
			</view>
			<view class="screen-icon" @click="showScreen">
                <image v-if="iconFlag === true" src="@/static/image/index/icon2.png" mode="widthFix"/>
                <image v-else src="@/static/image/index/icon1.png" mode="widthFix"/>
			</view>
		</view>
		<view class="list-container">
      <scroll-view scroll-y="true" refresher-enabled="true" :refresher-triggered="triggered" :lower-threshold="50"
                   :style="{height: `calc(100vh - 44px - 66px - ${TopHeight.top}px)`}" @scrolltolower="nextPage" :refresher-threshold="80"
                   refresher-background="rgb(244, 244, 244)" @refresherpulling="onPulling" @refresherrefresh="onRefresh"
                   @refresherrestore="onRestore" @refresherabort="onAbort">
        <view class="item" v-for="(item, index) in dataList" :key="index">
          <view class="img"   @click="toInfo(item.id)">
            <image :src="item.filePath"></image>
            <view class="statu" :class="{ green: item.lawStatus=='40'}">{{ item.lawStatus=='10'?'待上传':(item.lawStatus=='20' && item.rectifyStatus=='20')?'待审核':(item.lawStatus=='20' && item.rectifyStatus=='10')?'待整改':item.lawStatus=='30' ?'待复查':'已完成'}}</view>
          </view>
          <view class="info">
            <view    @click="toInfo(item.id)">
              <view class="row">
                <view class="title" v-if="queryForm.entryType=='6'">配餐单位:</view>
                <view class="title" v-else>学校名称:</view>
                <view class="con">{{ item.schoolName }}</view>
              </view>
              <view class="row">
                <view class="title">指标名称:</view>
                <view class="con">{{ item.targetName }}</view>
              </view>
              <view class="row">
                <view class="title">检查日期:</view>
                <view class="con">{{ item.lawDate }}</view>
              </view>
              <view class="row sign">
                <view class="title" style="width: 150rpx">检查人签名:</view>
                <view class="con">
                  <image :src="item.superviseSign" mode="heightFix"></image>
                </view>
              </view>
            </view>
            <view class="btn-row" v-if="item.lawStatus=='10'">
              <button @click="goToUpload(item)">上传记录单</button>
              <button @click="exportBill(item)">导出记录单</button>
            </view>
            <view class="btn-row" v-if="item.lawStatus=='20' && item.rectifyStatus=='20'">
              <button @click="goToExamine(item)">审核</button>
            </view>
            <view class="btn-row" v-if="item.lawStatus == '30'">
              <button @click="goToReview(item)">复查</button>
            </view>
            <view class="btn-row"
                  v-if="item.lawStatus == '40'">
              <button @click="getInspectionReport(item)">检查报告</button>
              <button v-if="item.rectifyFlag=='1'"  @click="getRectifyReport(item)">整改报告</button>
            </view>
          </view>
        </view>
        <view v-if="emptyFlag" class="empty-box">
          <uv-empty mode="data" icon="/static/image/no-data.png" width="200rpx" height="260rpx" text="&nbsp;"/>
        </view>
        <uv-gap height="136rpx"></uv-gap>
      </scroll-view>
		</view>
		<view class="check-bottom-box" @click.stop>
			<button class="sure-button" @click.stop="toCreate()">创建检查</button>
		</view>

		<!--筛选弹层-->
		<uv-popup ref="popup" @change="changeIcon" :closeable="true">
			<view class="popup-title">筛选</view>
			<view class="popup-content">
				<view class="popup-title-row">
					<text>检查日期</text>
				</view>
				<view class="popup-date-row">
					<view class="date" @click="showCalendar()">{{ startDate }}</view>
					<view class="to">至</view>
					<view class="date" @click="showCalendar()">{{ endDate }}</view>
					<uv-calendars ref="calendar" mode="range" reset-text="清空" @reset="dateReset" @confirm="dateConfirm" allowSameDay="true"></uv-calendars>
				</view>
        <div v-if="queryForm.entryType!=6">
          <view class="popup-title-row">
            <text>办学性质</text>
          </view>
          <view class="popup-con-row">
            <view class="item" :class="{actived:queryForm.lawDetail.schoolPropertiesCode==item.value}" v-for="(item,index) in natureList" :key="index"
                  @click="queryForm.lawDetail.schoolPropertiesCode =
      queryForm.lawDetail.schoolPropertiesCode === item.value ? '' : item.value;">{{item.name}}</view>
          </view>
          <view class="popup-title-row">
            <text>办学类型</text>
          </view>
          <view class="popup-con-row">
            <view class="item" :class="{ actived: queryForm.lawDetail.doSchoolTypeCode == item.value }" v-for="(item, index) in typeList"
                  :key="index" @click="schoolNatureFun(item)">
              {{ item.name }}
            </view>
          </view>
        </div>
        <view class="popup-title-row" v-if="areaList.length>0">
          <text>地区</text>
        </view>
        <view class="popup-con-row">
          <view v-for="(item,index) in areaList" :key="index" class="item"
                :class="{actived:item.code === area}" @click="areaFun(item)">
            {{ item.name }}
          </view>
        </view>
				<view class="bottom-box" @click.stop>
					<button class="yellow-sure-button" style="width: 49%" @click.stop="resetForm()">重置</button>
					<button class="sure-button" @click.stop="popupSubmit()">确认</button>
				</view>
			</view>
		</uv-popup>
	</view>
</template>

<script setup>
import { getCurrentInstance,reactive, ref } from 'vue';
import supLawApi from "@/api/law/supLaw/supLaw";
import dictApi from "@/api/dict/dict";
import {onLoad} from "@dcloudio/uni-app";
import publicAPI from "@/api/law/public/public";
const {proxy} = getCurrentInstance();
import config from "@/common/config";
let imgMinioPath = ref(config.IMG_MINIO_PATH);
const freshing = ref(false);
const triggered = ref(false);
const emptyFlag = ref(false);
const loadingType = ref('noMore');
const contentText = reactive({
  contentdown: "上拉显示更多",
  contentrefresh: "正在加载...",
  contentnomore: "没有更多数据了"
});
import TopHeight from "@/common/topHeight"
import dayjs from "dayjs";
const userInfo = ref(uni.getStorageSync('userInfo'));
const searchTitle = ref("");
const title = ref("");
const total = ref(0);
let iconFlag = ref(false);
const queryForm = reactive({ // 查询条件
  pageSize: 10,
  pageNum: 1,
  createOrgId:userInfo.value.user.orgId,
  entryType:"1",
  lawStatus:"10",
  lawType:"1",
  schoolName:'',
  params:{
    lawStartDate: '',
    lawEndDate: ''
  },
  lawDetail:{
    schoolPropertiesCode:null, //选中的学校性质
    doSchoolTypeCode:null,//选中的办学类型
  }
});

const calendar = ref();

//列表
const dataList = reactive([]);
//学校性质
let natureList = ref([]);
//
let typeList = ref([]);

const startDate = ref('开始日期');

const endDate = ref('结束日期');

//获取参数
onLoad((option) => {
  if (option.entryType) {
    queryForm.entryType = option.entryType;
    uni.setStorageSync('entryType', queryForm.entryType);
    if (queryForm.entryType == '1') {
      title.value = '食品安全日常检查';
      searchTitle.value = '学校名称';
    }else if (queryForm.entryType == '2') {
      title.value = '校园安全日常检查';
      searchTitle.value = '学校名称';
    }else if (queryForm.entryType == '7') {
      title.value = '学校有害生物检查';
      searchTitle.value = '学校名称';
    }else {
      title.value = '配餐单位执法检查';
      searchTitle.value = '配餐单位名称';
    }
  }
});
/** 筛选-地区 */
const area = ref('');
const areaList = ref([]);
let areaType = ref('');
// 获取地区列表
let getAreaList = async () => {
  let query = {};
  if (userInfo.value.user.org.county) { // 区
    areaType.value = '3';
    return;
  } else if (userInfo.value.user.org.city) { // 市
    areaType.value = '2';
    query.parentCode = userInfo.value.user.org.city;
  } else { // 省
    areaType.value = '1';
    query.parentCode = userInfo.value.user.org.province;
  }
  let res = await proxy.http.asyncPost(publicAPI.getAreaListByParentCode(query.parentCode));
  if (res.code === 0) {
    areaList.value = reactive(res.data);
  }
};
// 筛选选中
const areaFun = (item) => {
  if (area.value === item.code) {
    area.value = ''
  } else {
    area.value = item.code;
  }
};
let searchList = () => {
  queryForm.pageNum = 1;
  getsupLawPage();
};
//获取列表
let getsupLawPage = async () => {
  let res = await proxy.http.asyncPost(supLawApi.getsupLawPage, queryForm);
  if (res.code === 0) {
    total.value = res.data.total;
    if (queryForm.pageNum === 1) {
      dataList.length = 0;
    }
    dataList.push(...res.data.records);
    if (dataList.length < total.value) {
      loadingType.value = 'more';
    } else {
      loadingType.value = 'noMore'; //没有数据时显示‘没有更多’
    }
    emptyFlag.value = dataList.length <= 0;
  } else {
    await uni.showToast({title: res.msg, icon: 'none'});
  }
}
//获取码表-学校性质
let getNatureList = async () => {
  let res = await proxy.http.asyncGet(dictApi.findDataListByType('school_properties'), {});
  if (res.code === 0) {
    natureList.value =  [...res.data];
  }
}
//获取码表-办学类型
let getTypeList = async () => {
  let res = await proxy.http.asyncGet(dictApi.findDataListByType('do_school_type'), {});
  if (res.code === 0) {
    typeList.value = [...res.data];
  }
}
const list = ref([
	{
    id: 10,
		name: '待上传检查记录单'
	},
	{
    id: 20,
		name: '待审核'
	},
	{
    id: 30,
		name: '待复查'
	},
	{
    id: 40,
		name: '已完成'
	}
]);
const current = ref(0);

//点击tab切换
function changeTab(e) {
  queryForm.lawStatus = e.id;
  current.value= e.index;
  resetForm();
}
//弹出开始时间选择
function showCalendar() {
	calendar.value.open();
}
function dateConfirm(e) {
  console.info("dateConfirm",e);
  if (!e.range || !e.range.before || !e.range.after) {
    return ;
  }
  startDate.value = e.range.before;
  endDate.value = e.range.after;

}

let popup = ref();
//显示筛选弹层
function showScreen() {
	popup.value.open('bottom');
}

function popupSubmit() {
  if (startDate.value !== '开始日期') {
    queryForm.params.lawStartDate = startDate.value;
  }else{
    queryForm.params.lawStartDate = '';
  }
  if (endDate.value !== '结束日期') {
    queryForm.params.lawEndDate = endDate.value;
  }else{
    queryForm.params.lawEndDate ='';
  }
  if (areaType.value === '1') {
    queryForm.lawDetail.cityId = area.value;
  } else {
    queryForm.lawDetail.countyId = area.value;
  }
  popup.value.close();
  searchList();
}
let changeIcon = () => {
    if (queryForm.params.lawStartDate || queryForm.params.lawEndDate ||
        queryForm.lawDetail.cityId || queryForm.lawDetail.countyId ||
        queryForm.lawDetail.schoolPropertiesCode || queryForm.lawDetail.doSchoolTypeCode ) {
        iconFlag.value = true;
    } else {
        iconFlag.value = false;
    }
}
function resetForm() {
  iconFlag.value = false;
  startDate.value = '开始日期';
  endDate.value = '结束日期';
  area.value = '';
  queryForm.schoolName= '';
  queryForm.lawDetail.schoolPropertiesCode=null;
  queryForm.lawDetail.doSchoolTypeCode=null;
  queryForm.lawDetail.cityId = '';
  queryForm.lawDetail.countyId = '';
  queryForm.params.lawStartDate = '';
  queryForm.params.lawEndDate = '';
  searchList();
  popup.value.close();
}
function dateReset(){
  startDate.value = '开始日期';
  endDate.value = '结束日期';
}
const data = ref({});
//跳转查看信息页面
function toInfo(id) {
	uni.navigateTo({
		url: '/packageLawEnforcement/pages/viewInfo/viewDetail?id=' + id
	});
}
//跳转开始创建
function toCreate() {
  uni.navigateTo({
    url: `/packageLawEnforcement/pages/createCheck/index`,
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}
// 跳转上传检查记录单
function goToUpload(item) {
  let data={
    id:item.id,
    canteenId:item.canteenId,
    schoolId:item.schoolId
  }
  uni.navigateTo({
    url: `/packageLawEnforcement/pages/uploadRecord/index?data=${encodeURIComponent(JSON.stringify(data))}`,
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}
// 审核
function goToExamine(item) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/rectify/rectifyFormIndex?id=' + item.id,
    success: () => {
      uni.$once("refresh", () => {
        searchFun();
      });
    }
  });
}
// 复查
function goToReview(item) {
  uni.navigateTo({
    url: '/packageLawEnforcement/pages/review/index?id=' + item.id,
    success: () => {
      uni.$once("refresh", (index) => {
        searchFun();
      });
    }
  });
}
/** 滚动视图区域 */
    // 翻页
let nextPage = () => {
      if (queryForm.pageNum * queryForm.pageSize < total.value) {
        queryForm.pageNum++;
        getsupLawPage()
      }
    }
// 下拉
let onPulling = () => {
  freshing.value = false;
  setTimeout(() => {
    triggered.value = true;
  }, 1000)
};
// 刷新
let onRefresh = () => {
  if (freshing.value) return;
  triggered.value = 'restore';
  setTimeout(() => {
    freshing.value = false;
    triggered.value = false;
  }, 1000)
  //获取数据的函数
  queryForm.pageNum = 1 // 记录数
  getsupLawPage()
};
let onRestore = () => {
  triggered.value = 'restore'; // 需要重置
};
let onAbort = () => {
  console.log("onAbort");
};

// 检查报告
let getInspectionReport= async (item) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawPdfById(item.id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName + '记录单.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                          // 添加分享
                          uni.onShareAppMessage(function () {});
                      }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });

}


/** 导出记录单按钮 */
let exportBill = async (item) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawRecordPdfById(item.id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName +'记录单.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                          // 添加分享
                          uni.onShareAppMessage(function () {});
                      }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });
}
/** 导出记录单按钮 */
let getRectifyReport = async (item) => {
  uni.showLoading({title: '下载中', mask: true});
  let header = proxy.http.handleHeader('HEADER_JSON', '', false)
  uni.downloadFile({ //只能是GET请求
    url: supLawApi.downloadLawRectifyPdfById(item.id),//下载地址接口返回
    header: header,
    success: (res) => {
      //下载成功
      if (res.statusCode === 200) {
        //保存文件
        let tempFile = res.tempFilePath;
        //文件名称
        let fileName = dayjs(new Date()).format('YYYY.MM.DD') + item.schoolName + item.targetName;
        //保存成功之后 打开文件
        uni.getFileSystemManager().saveFile({
          tempFilePath: tempFile,
          filePath: wx.env.USER_DATA_PATH + '/' + fileName +' 整改报告.pdf',//自定义文件名
          success(red) {
            uni.showModal({
              title: '提示',
              content: '文件已保存：' + red.savedFilePath,
              cancelText: '我知道了',
              confirmText: '打开文件',
              success: function (res) {
                if (res.confirm) {
                  uni.openDocument({
                    filePath: red.savedFilePath,
                      showMenu: true,
                      success: (sus) => {
                          // 添加分享
                          uni.onShareAppMessage(function () {});
                      }
                  })
                }
              }
            });
          }
        })
      }
      uni.hideLoading();
    },
    fail: (e) => {
      console.log(e, '文件下载失败')
      uni.showToast({
        title: '文件下载失败',
        icon: "error",
      })
      uni.hideLoading();
    }
  });
}

/** 搜索 */
let searchFun = () => {
  queryForm.pageNum = 1;
  searchList();
};

/** 清空搜索 */
let clearFun = () => {
  searchFun();
}
function schoolNatureFun(item){
  if(queryForm.lawDetail.doSchoolTypeCode === item.value){
    queryForm.lawDetail.doSchoolTypeCode =  ''
    return
  }
  queryForm.lawDetail.doSchoolTypeCode = item.value
}
//页面加载
onMounted(async () => {
  searchList();
  getNatureList();
  getTypeList();
  getAreaList();
})
</script>

<style lang="scss" scoped>

.btn-row {
  width: 250px!important;
}


.bottom-box {
	padding: 0;

	.sure-button {
		width: 49% !important;
	}
}
.list-container{
  .item{
    padding: 20rpx!important;
  }
}
.popup-con-row{
  .item{
    display: flex!important;
    align-items: center!important; /* 垂直居中 */
    justify-content: center!important; /* 水平居中，可选 */
  }
}

.btn-row{
  margin-top: 30rpx!important;
  position: unset!important;
  padding-right:20rpx!important;
}
</style>
